package com.tom.architect02.other.ui;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.tom.architect02.R;

/**
 * Added by Tom on 2024/03/14.
 * 自定义TextView
 */
public class MNView extends View {
    private final Paint mPaint;
    private int color;
    private String text;
    private int mWidth;
    private int mHeight;
    // 计算字体需要的范围
    private Rect mTextBounds;  // drawText有一个基准线

    public MNView(Context context) {
        this(context, null);
    }

    public MNView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MNView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MNView);
        color = ta.getInteger(R.styleable.MNView_mn_color, R.color.purple_200);
        text = ta.getString(R.styleable.MNView_mn_text);
        ta.recycle();

        // 初始化画笔
        mPaint = new Paint();
        mTextBounds = new Rect();
        mPaint.setColor(color);
        mPaint.setTextSize(50);
        // text转换为 bounds
        mPaint.getTextBounds(text, 0, text.length(), mTextBounds);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specWidth = MeasureSpec.getSize(widthMeasureSpec);
        if (specMode == MeasureSpec.EXACTLY) {
            // 子view指定了match_parent或 指定了具体的数值
            mWidth = specWidth;
        } else {
            // at_most: 空间大小，跟字体大小来定 处理warp_content
            mWidth = mTextBounds.width() + getPaddingLeft() + getPaddingRight();
        }
        specMode = MeasureSpec.getMode(heightMeasureSpec);
        int specHeight = MeasureSpec.getSize(heightMeasureSpec);
        if (specMode == MeasureSpec.EXACTLY) {
            mHeight = specHeight;
        } else {
            // at_most: 处理warp_content
            mHeight = mTextBounds.height() + getPaddingTop() + getPaddingBottom();
        }

        // 确定当前控件，最终的大小
        setMeasuredDimension(mWidth, mHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(text, getPaddingLeft() + 0, getPaddingTop() + mTextBounds.height(), mPaint);
    }
}
